package com.mall.order.biz.handler;

import com.mall.commons.tool.exception.BizException;
import com.mall.order.biz.context.CreateOrderContext;
import com.mall.order.biz.context.TransHandlerContext;
import com.mall.order.constant.OrderRetCode;
import com.mall.order.constants.OrderConstants;
import com.mall.order.dal.entitys.Order;
import com.mall.order.dal.entitys.OrderItem;
import com.mall.order.dal.persistence.OrderItemMapper;
import com.mall.order.dal.persistence.OrderMapper;
import com.mall.order.dto.CartProductDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.UUID;

/**
 *  ciggar
 * create-date: 2019/8/1-下午5:01
 * 初始化订单 生成订单
 */

@Slf4j
@Component
public class InitOrderHandler extends AbstractTransHandler {

    @Autowired
    private OrderMapper orderMapper;

    @Autowired
    private OrderItemMapper orderItemMapper;

    @Override
    public boolean isAsync() {
        return false;
    }

    @Override
//    @Transactional(rollbackFor = Exception.class)
    public boolean handle(TransHandlerContext context) {

        CreateOrderContext createOrderContext = (CreateOrderContext) context;

        // 插入订单
        Order order = new Order();
        Date date = new Date();
        // 后期用全局id生成器 todo lsy
        String orderId = UUID.randomUUID().toString();
        order.setOrderId(orderId);
        order.setUserId(createOrderContext.getUserId());
        order.setBuyerNick(createOrderContext.getUserName());
        // 未支付
//        order.setPayment(null);
        order.setCreateTime(date);
        order.setUpdateTime(date);
        order.setUniqueKey(createOrderContext.getUniqueKey());
        // 买家评论
//        order.setBuyerComment(null);
        // 买家留言
//        order.setBuyerMessage(null);
        // 关闭时间
//        order.setCloseTime(null);
        // 发货时间
//        order.setConsignTime(null);
        // 交易完成时间
//        order.setEndTime(null);
        // 支付时间
//        order.setPaymentTime(null);
        // 支付类型
//        order.setPaymentType();
        // 邮费
//        order.setPostFee();
        // 物流单号
//        order.setShippingCode();
        // 物流名称
//        order.setShippingName();
        order.setStatus(OrderConstants.ORDER_STATUS_INIT);
        try {
            int insert = orderMapper.insert(order);
            if (insert != 1) {
                throw new Exception();
            }
        } catch (Exception e) {
            log.error(OrderRetCode.ORDER_DB_SAVED_FAILED.getMessage());
            throw new BizException(OrderRetCode.ORDER_DB_SAVED_FAILED.getCode(), OrderRetCode.ORDER_DB_SAVED_FAILED.getMessage());
        }

        ArrayList<Long> buyProductIds = new ArrayList<>();
        // 插入订单商品关联表
        List<CartProductDto> cartProductDtoList = createOrderContext.getCartProductDtoList();
        for (CartProductDto cartProductDto : cartProductDtoList) {
            OrderItem orderItem = new OrderItem();

            String orderItemId = UUID.randomUUID().toString();
            BigDecimal totalFee = cartProductDto.getSalePrice().multiply(new BigDecimal(cartProductDto.getProductNum()));

            orderItem.setId(orderItemId);
            orderItem.setItemId(cartProductDto.getProductId());
            orderItem.setOrderId(orderId);
            orderItem.setNum(cartProductDto.getProductNum().intValue());
            orderItem.setPrice(cartProductDto.getSalePrice().doubleValue());
            orderItem.setTitle(cartProductDto.getProductName());

            // 图片取第一个，逗号隔开的
            String productImgs = cartProductDto.getProductImg();
            String productImg = productImgs.split(",")[0];
            orderItem.setPicPath(productImg);

            orderItem.setTotalFee(totalFee.doubleValue());
            // 已经锁定库存
            orderItem.setStatus(1);

            buyProductIds.add(cartProductDto.getProductId());

            try {
                int insert = orderItemMapper.insert(orderItem);
                if (insert != 1) {
                    throw new Exception();
                }
            } catch (Exception e) {
                log.error(OrderRetCode.ORDERITEM_DB_SAVED_FAILED.getMessage());
                throw new BizException(OrderRetCode.ORDERITEM_DB_SAVED_FAILED.getCode(), OrderRetCode.ORDERITEM_DB_SAVED_FAILED.getMessage());
            }

        }

        createOrderContext.setOrderId(orderId);


        createOrderContext.setBuyProductIds(buyProductIds);

        return true;
    }
}
